<script>
import { getAdminiDiv } from '@/api/mscInfo'
export default {
  name: 'Address',
  inheritAttrs: false,
  props: {
    value: {
      type: [Number, String],
      default: ''
    },
    name: {
      type: [String],
      default: ''
    },
    parent: {
      type: String,
      default: ''
    },
    label: {
      type: String,
      default: ''
    },
    labelWidth: {
      type: String,
      default: '0px'
    },
    option: {
      type: String,
      default: 'id'
    },
    init: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      optionsList: [],
      slectValue: ''
    }
  },
  watch: {
    parent: {
      handler: 'getAdminiDiv',
      immediate: true
    },
    value: {
      handler() {
        this.slectValue = this.value
      },
      immediate: true
    }
  },
  methods: {
    getAdminiDiv() {
      if (!this.parent && !this.init) {
        this.optionsList = []
        this.slectValue = ''
        this.$emit('input', '')
        this.$emit('update:name', '')
        return
      }
      if (this.parent && this.slectValue) {
        this.optionsList = []
        this.slectValue = ''
        this.$emit('input', '')
        this.$emit('update:name', '')
      }
      getAdminiDiv({ id: this.parent }).then(res => {
        this.optionsList = res.data
      })
    }
  },
  render(h) {
    const options = []
    for (const item of this.optionsList) {
      options.push(h('el-option', {
        key: item.id,
        props: {
          value: item[this.option],
          label: item.name
        }
      }))
    }
    const select = h('el-select', {
      props: {
        value: this.slectValue,
        ...this.$attrs,
        disabled: (!this.parent && !this.init) || this.disabled
      },
      style: {
        flex: `1 1 calc(100% - ${this.labelWidth})`,
        width: `calc(100% - ${this.labelWidth})`
      },
      on: {
        change: v => {
          this.$emit('input', v)
          if (v === undefined || v === '' || v === null) {
            this.$emit('update:name', '')
            return
          }
          for (const item of this.optionsList) {
            if (v === item[this.option]) {
              this.$emit('update:name', item.name)
              break
            }
          }
        }
      }
    }, options)
    return h('div', {
      style: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }
    }, [
      h('span', {
        style: {
          flex: `0 0 ${this.labelWidth}`,
          paddingRight: '5px',
          color: '#333333',
          fontSize: '12px',
          fontWeight: 'normal'
        }
      }, this.label),
      select
    ])
  }
}
</script>
<style lang='scss' module>
</style>
